# -*- coding: utf-8 -*-
"""
Created on Sat Dec 29 17:28:03 2018

@author: 5
"""

from flask import Flask,make_response
from flask_cors import CORS
#from pypinyin import pinyin, lazy_pinyin, Style
from xpinyin import Pinyin

from flask import request

import json
import operate_es

#def get_pinyin(column_chinese):
#    return ''.join(lazy_pinyin(column_chinese))
print("beginto new app")
app = Flask(__name__)
CORS(app, supports_credentials=True)

esutil = operate_es.Elasticdemo('info_manager','columns','localhost',9200)
@app.route('/')
def test_1():   
    return "Hello, World!"

@app.route('/testjson')
def test():
    t = {
        'columns': ['xingming','nianling','chushengriqi','工作日期'],
        'rows': [{'xingming':'张三','nianling':'20','chushengriqi':'1990.01.23','工作日期':'2018.01.09'},
                 {'xingming':'李四','nianling':'30','chushengriqi':'1991.01.24','工作日期':'2018.01.10'},
                 {'xingming':'王五','nianling':'40','chushengriqi':'1992.01.25','工作日期':'2018.01.11'},
                 {'xingming':'xiaowang','nianling':'16','chushengriqi':'1993.01.26','工作日期':'2018.01.12'}]
    }
    return json.dumps(t,ensure_ascii=False).encode("utf-8") 

@app.after_request
def af_request(resp):     
    """
    #请求钩子，在所有的请求发生后执行，加入headers。
    :param resp:
    :return:
    """
    resp = make_response(resp)
    resp.headers['Access-Control-Allow-Origin'] = '*'
    resp.headers['Access-Control-Allow-Methods'] = 'GET,POST'
    resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return resp


"""
添加列rest接口
"""
@app.route('/add_column') 
def add_column():
    app.logger.info(request.args)
    app.logger.info(request.form)
    column_desc = request.args.get("column_name")
    app.logger.info(column_desc)
    pin = Pinyin()
    column_name = pin.get_pinyin(column_desc,"")
    true=esutil.exists_column(column_name)["total"]
    print(true)
    if(true>0):
#        print("该列已存在,请重新输入属性的名字和值，格式如：身高,175")
        ret="404"
        msg="该列已存在"
        r = {'ret_code':ret, 'msg':msg}
        return json.dumps(r,ensure_ascii=False).encode("utf-8") 
    else:
        column_type = request.args.get("column_type")
        if None == column_type:
            column_type = 'string'
        default_value = request.args.get("default_value")
        if None == default_value:
            default_value = '世界一流'
        column_json = {'column_desc':column_desc, 
                       'column_name':column_name,
                       'column_type':column_type,
                       'default_value':default_value}
        ret,msg = esutil.add_column(column_json)
        r = {'ret_code':ret, 'msg':msg}
        return json.dumps(r,ensure_ascii=False).encode("utf-8") 

"""
删除列rest接口
"""
#[{'total': 1}, {'id', '0eGVS2gBeU-m1JYwdJw8'}]
@app.route('/del_column') 
def del_column():
    app.logger.info(request.args)
    app.logger.info(request.form)
    column_desc = request.args.get("column_name")
    app.logger.info(column_desc)
    pin = Pinyin()
    column_name = pin.get_pinyin(column_desc,"")
    true=esutil.exists_column(column_name)["total"]
    if(true == 0):
#        print("该列已存在,请重新输入属性的名字和值，格式如：身高,175")
        ret="404"
        msg="该列不存在"
        r = {'ret_code':ret, 'msg':msg}
        return json.dumps(r,ensure_ascii=False).encode("utf-8") 
    else:
        id=esutil.exists_column(column_name)["id"]
        ret,msg = esutil.delete_single(id)
        r = {'ret_code':ret, 'msg':msg}
        return json.dumps(r,ensure_ascii=False).encode("utf-8") 

@app.route('/query_column') 
def query_column():
    app.logger.info(request.args)
    app.logger.info(request.form)
    column_desc = request.args.get("column_name")
    app.logger.info(column_desc)
    pin = Pinyin()
    column_name = pin.get_pinyin(column_desc,"")
    true=esutil.exists_column(column_name)["total"]
    if(true == 0):
#        print("该列已存在,请重新输入属性的名字和值，格式如：身高,175")
        ret="404"
        msg="该列不存在"
        r = {'ret_code':ret, 'msg':msg}
        return json.dumps(r,ensure_ascii=False).encode("utf-8") 
    else:
        id=esutil.exists_column(column_name)["id"]
        ret = 200
        msg = esutil.get_single(id)
        r = {'ret_code':ret, 'msg':msg[0]['data']}
        return json.dumps(r,ensure_ascii=False).encode("utf-8") 

if __name__ =="__main__":
    print("begin to start server ")
    app.run(debug=True,host="10.3.0.16",port=5000)
    print("end to start server ")
    
